package com.leoandroid.tool.toolsbox.largeread.activity;

import android.annotation.SuppressLint;
import android.app.RecoverableSecurityException;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.github.chrisbanes.photoview.PhotoView;
import com.leoandroid.tool.toolsbox.largeread.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImagePreviewActivity extends BaseActivity{

    private static final String TAG = "ImagePreviewActivity";
    private View cautionTopMask;

    private View cautionBottomMask;
    private LinearLayout layoutBack;
    private LinearLayout layoutDelete;
    private PhotoView photoView;
    private TextView tvSave;

    private String imgPath;

    private static final int MSG_CAUTION_MASK_TOP = 1;
    private static final int MSG_CAUTION_MASK_BUTTON = 2;


    private static final int DELAY_TIME = 200;


    @SuppressLint("HandlerLeak")
    private Handler mhandler = new  Handler(){
        // 通过复写handlerMessage()从而确定更新UI的操作
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG_CAUTION_MASK_TOP:
                    cautionTopMask.setVisibility(View.VISIBLE);
                    cautionBottomMask.setVisibility(View.GONE);
                    mhandler.sendEmptyMessageDelayed(MSG_CAUTION_MASK_BUTTON, DELAY_TIME);
                    break;
                case MSG_CAUTION_MASK_BUTTON:
                    cautionTopMask.setVisibility(View.GONE);
                    cautionBottomMask.setVisibility(View.VISIBLE);
                    mhandler.sendEmptyMessageDelayed(MSG_CAUTION_MASK_TOP, DELAY_TIME);
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_preview);
        Intent intent = getIntent();
        imgPath = intent.getStringExtra("path");
        initView();
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        photoView.setImageBitmap(bitmap);
        photoView.setDrawingCacheEnabled(true);
//        mhandler.sendEmptyMessageDelayed(MSG_CAUTION_MASK_TOP, DELAY_TIME);
    }

    private void initView(){
        cautionTopMask = findViewById(R.id.caution_top_mask);
        cautionBottomMask = findViewById(R.id.caution_bottom_mask);
        layoutBack = findViewById(R.id.preview_back);
        layoutDelete = findViewById(R.id.preview_delete);
        photoView = findViewById(R.id.photo_view);
        tvSave = findViewById(R.id.preview_save);

        layoutBack.setOnClickListener(view -> {
            finish();
        });
        layoutDelete.setOnClickListener(view -> {
            ContentResolver resolver = this.getContentResolver();	// 通过context上下文可拿到
            Cursor cursor = MediaStore.Images.Media.query(resolver,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    new String[]{MediaStore.Images.Media._ID},
                    MediaStore.Images.Media.DATA + "=?",
                    new String[]{imgPath}, null);
            if (null != cursor && cursor.moveToFirst()) {
                long id = cursor.getLong(0);
                Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                Uri uri = ContentUris.withAppendedId(contentUri, id);
                deleteImage(uri);
                finish();
            }
        });

        tvSave.setOnClickListener(view -> {
            Bitmap bitmap = photoView.getDrawingCache(true);
            if(bitmap != null){
                saveImageToGallery(this, bitmap);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_DELETE_IMAGE) {
            if (resultCode == RESULT_OK) {
                // 用户授予修改图片权限，再次执行删除操作
                if(data != null){
                    deleteImage(data.getData());
                    finish();
                }
            }
        }
    }


    public void saveImageToGallery(Context context, Bitmap bmp)
    {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DCIM + File.separator + "largeRead");
        if (!appDir.exists())
        {
            Log.e(TAG, "去创建文件夹");
            appDir.mkdirs();
        }
        String fileName = "largeRead_" + System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try
        {
            Log.e(TAG, "开始保存图片");
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            // 最后通知图库更新
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
            Toast.makeText(context, "图片保存成功 ", Toast.LENGTH_LONG).show();
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
            Log.e(TAG, "保存图片失败:" + e.toString());
            Toast.makeText(context, "图片保存失败,请开启存储权限", Toast.LENGTH_LONG).show();
        } catch (IOException e)
        {
            e.printStackTrace();
            Log.e(TAG, "保存图片失败:" + e.toString());
            Toast.makeText(context, "图片保存失败,请开启存储权限", Toast.LENGTH_LONG).show();
        }
    }

    public static final int REQUEST_CODE_DELETE_IMAGE = 1001;
    public void deleteImage(Uri imgUri) {
        Log.d(TAG, "deleteImage_uri:" + imgUri);
        ContentResolver mContentResolver = getContentResolver();
        try {
            // 对于未启用分区存储的情况，若权限申请到位，则以下代码可以执行成功直接删除
            int count = mContentResolver.delete(imgUri, null, null);
            boolean result = (count == 1);
            if(result){
                Toast.makeText(getApplicationContext(), "图片删除成功 ", Toast.LENGTH_LONG).show();
            }
            Log.d(TAG, "DeleteImage result:" + result);
        } catch (SecurityException exception) {
            // 若启用了分区存储，上面代码delete将会报错，显示没有权限。
            // 需要捕获这个异常，并用下面代码，使用startIntentSenderForResult弹出弹窗向用户请求修改当前图片的权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                RecoverableSecurityException recoverableSecurityException;
                if (exception instanceof RecoverableSecurityException) {
                    recoverableSecurityException = (RecoverableSecurityException)exception;
                } else {
                    throw new RuntimeException(exception.getMessage(), exception);
                }
                IntentSender intentSender = recoverableSecurityException.getUserAction().getActionIntent().getIntentSender();
                try {
                    startIntentSenderForResult(intentSender, REQUEST_CODE_DELETE_IMAGE,null, 0, 0, 0, null);
                } catch (IntentSender.SendIntentException e) {
                    e.printStackTrace();
                }
            } else {
                throw new RuntimeException(exception.getMessage(), exception);
            }
        }
    }

}
